<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    :showFooter="true"
    :title="getTitle"
    width="800px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { formSchema } from './menu.data';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';

  import { addMenuItem, editMenuItem } from '@/api/system/system';
  import { isUnDef } from '@/utils/is';
  import { cloneDeep } from 'lodash-es';
  import { useMessage } from '@/hooks/web/useMessage';

  export default defineComponent({
    name: 'MenuDrawer',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const nMenuId = ref(-1);
      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: { lg: 12, md: 24 },
      });
      const { createMessage } = useMessage();

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        if (data.record?.id) nMenuId.value = data.record.id;
        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
          console.log(...data.record, '...data.record6556');
        }
        // const treeData = await getMenuList();
        // updateSchema({
        //   field: 'parent_id',
        //   // componentProps: { treeData },
        //   componentProps: {
        //     options: treeData,
        //   },
        // });
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增菜单' : '编辑菜单'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({ confirmLoading: true });
          let params = cloneDeep(values);
          if (isUnDef(params.parent_id)) params.parent_id = 0;
          if (unref(isUpdate)) params.id = unref(nMenuId);
          // dataCode 改成 code const data =
          unref(isUpdate) ? await editMenuItem(params as any) : await addMenuItem(params as any);
          unref(isUpdate)
            ? createMessage.success('修改菜单成功')
            : createMessage.success('新增菜单成功');
          // console.log(data, 'datas');
          // if (code === 200) {
          await closeDrawer();
          emit('success');
          // }
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return { registerDrawer, registerForm, getTitle, handleSubmit };
    },
  });
</script>
